<template>
    <div class="alloc-menu">
        <el-card>
            <div slot="header">
                <span>分配资源</span>
            </div>
            <el-tree
                ref="menu-tree"
                :data="menus" 
                node-key="id"
                :props="defaultProps"
                show-checkbox
                default-expand-all
                :default-checked-keys="checkedKeys"
            >
            </el-tree>
            <div style="text-align: center; margin: 10px">
                <el-button @click="resetChecked">清空</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getMenuNodeList, allocateRoleMenus, getRoleMenus } from '@/services/menu'
import { Tree } from 'node_modules/element-ui/types/element-ui'

export default Vue.extend({
    name: 'AllocMenu',
    props: {
        roleId: {
            type: [String, Number],
            required: true
        }
    },
    data () {
        return {
            menus: [],
            defaultProps: {
                children: 'subMenuList',
                label: 'name'
            },
            checkedKeys: []
        }
    },
    created () {
        this.loadMenus()
        this.loadRoleMenus()
    },
    methods: {
        async loadMenus () {
            const { data } = await getMenuNodeList()
            if (data.code === '000000') {
                this.menus = data.data
            }
        },
        async loadRoleMenus () {
            const { data } = await getRoleMenus(this.roleId)
            if (data.code === '000000') {
                this.getCheckedKeys(data.data)
            }
        },
        getCheckedKeys (menus: any) {
            menus.forEach((menu: any) => {
                if (menu.selected) {
                    // this.checkedKeys.push(menu.id as never)
                    this.checkedKeys = [...this.checkedKeys, menu.id] as any
                }
                if (menu.subMenuList) {
                    this.getCheckedKeys(menu.subMenuList)
                }
            })
        },
        // 保存
        async onSave () {
            // 拿到选中节点的数据 id 列表
            const menuIdList = (this.$refs['menu-tree'] as Tree).getCheckedKeys()
            // 请求提交保存
            const { data } = await allocateRoleMenus({
                roleId: this.roleId,
                menuIdList
            })
            if (data.data) {
                this.$message.success('保存成功')
                this.$router.push({
                    name: 'role'
                })
            }
        },
        // 清空
        resetChecked() {
            (this.$refs['menu-tree'] as Tree).setCheckedKeys([]);
        }
    }
})
</script>

<style lang="scss" scoped></style>
